package com.heima.admin.controller;

import com.heima.admin.entity.AdChannel;
import com.heima.admin.service.AdChannelService;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "频道管理",description = "频道管理API")
public class AdChannelController {

    @Autowired
    private AdChannelService adChannelService;
    /**
     * 分页查询频道信息
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据名称分页查询频道列表")
    @ApiImplicitParam(name = "dto", value = "频道请求对象", required = true, dataType = "ChannelDto")
    @PostMapping("/api/v1/channel/list")
    public PageResult<ChannelDto> findByPage(@RequestBody ChannelDto dto){
        return adChannelService.findByPage(dto);
    }

    /**
     * 保存
     * @param dto
     * @return
     */
    @PostMapping("/api/v1/channel/save")
    public ResponseResult save(@RequestBody ChannelDto dto){

        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        adChannel.setCreatedTime(new Date());
        adChannelService.save(adChannel);
        return ResponseResult.ok();
    }

    /**
     * 修改
     * @param channel
     * @return
     */
    @PutMapping("/api/v1/channel/update")
    public ResponseResult update(@RequestBody AdChannel channel){

        adChannelService.updateById(channel);
        return ResponseResult.ok();

    }

    /**
     * 删除频道
     * 如果是有效的频道，不能删除
     * @param channelId
     * @return
     */
    @DeleteMapping("/api/v1/channel/del/{id}")
    public ResponseResult delete(@PathVariable(name = "id")Integer channelId){

        AdChannel adChannel = adChannelService.getById(channelId);
        if(adChannel != null && adChannel.getStatus()){
//         如果启用状态 就不能删除
            throw new LeadException(AppHttpCodeEnum.DATA_CAN_NOT_DEL);
        }
        adChannelService.removeById(channelId);
        return ResponseResult.ok();
    }

    @GetMapping("/api/v1/channel/channels")
    public ResponseResult<List<AdChannel>> channels(){

        List<AdChannel> list = adChannelService.list();
        if(CollectionUtils.isEmpty(list)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.ok(list);

    }
}
